package com.retry.task.admin.infrastructure.scheduler;

import com.retry.task.admin.constants.SystemLocks;
import com.retry.task.admin.dal.model.RetryTaskGroupDO;
import com.retry.task.admin.dal.model.query.RetryTaskGroupQuery;
import com.retry.task.admin.utils.DateUtils;
import com.retry.task.core.utils.CommonExecuteUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author gao.gwq
 * @version 1.0
 * @date 2022/5/13  13:42
 * @Description TODO
 */
@Component
public class NoHeartCheckScheduler extends BaseScheduler {

    private static final Logger LOGGER = LoggerFactory.getLogger(NoHeartCheckScheduler.class);

    private Thread thread;

    @Override
    public void afterPropertiesSet() throws Exception {
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                LOGGER.info(">>>>>>>>>>>>>>retry-task no heart check start<<<<<<<<<<<<<<");
                while (true) {
                    boolean lockFlag = false;
                    try {
                        TimeUnit.SECONDS.sleep(300);
                        lockFlag = mysqlLock.tryLock(SystemLocks.NO_HEART_TICK_OVER_5_MIN, isTest);
                        if (lockFlag == false) {
                            continue;
                        }
                        process();
                    } catch (Exception ex) {
                        LOGGER.error("retry-task fail task check error {}", ex.getMessage(), ex);
                    } finally {
                        if (lockFlag == true) {
                            mysqlLock.releasLock(SystemLocks.NO_HEART_TICK_OVER_5_MIN, isTest);
                        }
                    }
                }

            }
        });
        thread.setDaemon(true);
        thread.setName("check fail task thread");
        thread.start();
    }

    public void process() {
        List<RetryTaskGroupDO> groupDOList = CommonExecuteUtils.findByQuery(1, 100, (page, limit) -> {
            RetryTaskGroupQuery query = new RetryTaskGroupQuery();
            query.setPageNum(page);
            query.setPageSize(limit);
            query.setIsTest(isTest);
            query.setStatus(1);
            query.setMinHeartTime(DateUtils.addMinute(new Date(), -5));
            return retryTaskGroupService.queryByRetryTaskGroups(query);
        });
        if (CollectionUtils.isEmpty(groupDOList)) {
            return;
        }
        for (RetryTaskGroupDO retryTaskGroupDO : groupDOList) {
            retryTaskGroupDO.setStatus(-1);
            retryTaskGroupService.updateRetryTaskGroupById(retryTaskGroupDO.getId(), retryTaskGroupDO);
        }
    }

}
